<template>
  <div
    class="avatar-wrap"
    :style="{
      width: width + 'px',
      height: height + 'px',
    }"
  >
    <el-image
      class="avatar"
      :src="src"
      :fit="fit"
      :style="{
        width: width + 'px',
        height: height + 'px',
      }"
      :preview-src-list="file ? [] : [src]"
    >
    </el-image>
    <input
      type="file"
      name="avatar"
      class="ipt"
      :style="{
        width: width + 'px',
        height: height + 'px',
        display: file ? 'block' : 'none',
        opacity: 0,
      }"
      @change="avatarChange"
    />
  </div>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      default: "",
    },
    fit: {
      type: String,
      default: "cover",
    },
    width: {
      type: Number,
      default: 100,
    },
    height: {
      type: Number,
      default: 100,
    },
    file: {
      type: Boolean,
      default: false,
    },
    cb: {
      type: Function,
      default: () => {},
    },
  },
  methods: {
    avatarChange(e) {
      let file = e.target.files[0];
      if (!file) return;
      let img_o = new Image();
      let url = window.URL || window.webkitURL;
      img_o.src = url.createObjectURL(file);
      // this.src = img_o.src; // 此处会报警告
      let imgBase_s;
      let self = this;
      img_o.onload = function () {
        imgBase_s = self.getBase64Image(this);
        self.cb(imgBase_s);
      };
    },
    getBase64Image(img) {
      var canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0, img.width, img.height);
      var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
      var dataURL = canvas.toDataURL("image/" + ext);
      return dataURL;
    },
  },
};
</script>

<style lang="less" scoped>
.avatar-wrap {
  position: relative;
  .ipt {
    position: absolute;
    left: 0;
    top: 0;
  }
  .avatar {
    background-color: rgb(192, 196, 204);
    background-repeat: no-repeat;
    background-position: center;
    border-radius: 4px;
  }
}
</style>